import React, { useEffect, useState } from 'react';
import { MyStations } from '../MyStations';
import { Timeline, message, Form, Select, Space, Button } from 'antd';
import { useDebounceFn } from 'ahooks';
import _ from 'lodash';
import { PageLoading } from '@/components/index.js';
import styles from './index.less';
import { tabOption_1 } from '../../helper.js';
import { UpSquareOutlined, DownSquareOutlined } from '#/utils/antdIcons.js';
import { TjStation } from '@/pages/ETrade/components/index.js';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';
import InfiniteScroll from 'react-infinite-scroller/index.js';
import moment from 'moment';
import { powerGenerationPlanOperateLog, useNewServers } from '../../services.js';
import { HttpCode } from '#/utils/contacts.js';

let flag = false;
interface props {
  stations: any[];
  treeData: any[];
  optionAll: any[];
  formData: any;
  defaultItem: object;
  treeHljData: any[];
  province: any[];
}

const HistoryShot = (props: props) => {
  const { stations, treeData, optionAll, defaultItem, treeHljData, province, formData } = props;
  const [unit, setUnit] = useState<any>([]),
    [pageSize] = useState(50),
    [loading, setLoading] = useState(false),
    [currentPage, setCurrentPage] = useState(1),
    [total, setTotal] = useState(-1),
    [logArray, setLogArray] = useState<any>([]),
    [form] = Form.useForm(),
    [currentProvinceInfo, setCurrentProvinceInfo] = React.useState<any>(),
    [curMarketId, setCurMarketId] = React.useState(''), //缓存当前选中的marketId
    [tradingUnitList, setTradingUnitList] = React.useState<any>([...formData?.stationIdList]);

  // useEffect(() => {
  //   onUnitChange(optionAll);
  // }, []);

  useEffect(() => {
    setCurMarketId(formData.marketId);
    const item = { value: formData.marketId };
    setCurrentProvinceInfo(item);
    // province 是父组件传的交易中心下拉选项
    if (province.length > 0) {
      // 选第一个交易中心作为默认
      // changeMarketId(province[0]?.value);
      // setCurMarketId(province[0]?.value);
      onUnitChange(form.getFieldValue('stationIdList'));
    }
  }, [province]);

  const getNewTableData = (data: any) => {
    return (data || [])
      .map((t: any, i: number) => {
        return {
          id: logArray.length + i,
          unit: t.stationName,
          planStatus: tabOption_1.find((_t: any) => t.status === _t.value)?.label,
          status: t.status,
          yearPlanTotal: parseFloat(t.yearEle).toFixed(3),
          date: t.planDateTime,
          operator: t.opUserName,
          planId: t.planId,
          unitId: t.stationId,
          operationYear: t.operationYear,
          data: t.monthPlan,
          expand: false,
          isYear: t.operateMethod === 'year',
        };
      })
      .sort((a: any, b: any) => b.date.localeCompare(a.date));
  };
  const searchData = async (param: any, type = 0) => {
    if (flag) return;
    flag = true;
    if (total === logArray.length && !type) {
      message.warning('没有更多数据');
      return;
    }

    if (useNewServers.includes(curMarketId ? curMarketId : formData.marketId)) {
      param.marketId = curMarketId ? curMarketId : formData.marketId;
    }

    const res = await powerGenerationPlanOperateLog(
      param,
      curMarketId ? curMarketId : formData.marketId,
    ).catch();
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data) return;
      setTotal(res.data.total);
      const data = res.data;
      const _temp = getNewTableData(data.records);
      setLogArray(type ? _temp : logArray.concat(_temp));
      flag = false;
    }
  };

  const onUnitChange = async (e: any) => {
    setLogArray([]);
    setTotal(-1);
    setLoading(true);
    setUnit(e);
    setCurrentPage(1);
    const param = {
      current: 1,
      size: pageSize,
      stationIdList: tradingUnitList,
      stationNameList: tradingUnitList.map(
        (t: any) => stations.find((_t: any) => t === _t.value)?.label,
      ),
    };
    await searchData(param, 1);
    setLoading(false);
  };

  const _onFinish = useDebounceFn(
    async (values: any) => {
      onUnitChange(form.getFieldValue('stationIdList'));
    },
    { wait: 500 },
  );

  const loadMore = () => {
    if (flag) return;
    setCurrentPage(currentPage + 1);
    const param = {
      current: currentPage + 1,
      size: pageSize,
      stationIdList: unit,
      stationNameList: unit.map((t: any) => stations.find((_t: any) => t === _t.value)?.label),
    };
    searchData(param);
  };

  //交易中心改变事件
  const changeMarketId = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      setCurrentProvinceInfo(item);
      setCurMarketId(item.value);
      form.setFieldsValue({
        stationIdList: item.stations.map((v: StationType) => {
          return v.stationId;
        }),
      });
    }
  };

  const initialValues = () => {
    // if (!optionAll.length) return;
    if (!treeHljData.length) return;
    return {
      marketId: formData.marketId,
      // marketId: province.length > 0 ? province[0].value : '',
    };
  };
  return (
    <div className={styles.container}>
      <div className={styles.head}>
        {/* <TjStation width={140} value={unit} options={treeData} onChange={onUnitChange} /> */}
        <Form
          form={form}
          initialValues={initialValues()}
          className={styles.formStyles}
          onFinish={_onFinish.run}
        >
          <Space size={8} wrap>
            <Form.Item name="marketId" className={styles.marketId_item}>
              <Select
                options={province}
                style={{ width: 120 }}
                placeholder="请选择交易中心"
                onChange={changeMarketId}
              />
            </Form.Item>

            <Form.Item name="stationIdList" className={styles.marketId_item}>
              <TjMarketingUnit
                treeData={treeHljData}
                marketId={currentProvinceInfo?.value}
                setTradingUnitList={setTradingUnitList}
                tradingUnitList={tradingUnitList}
              />
            </Form.Item>

            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
          </Space>
        </Form>
      </div>
      {loading ? (
        <PageLoading />
      ) : (
        <div className={styles.contentBox}>
          <InfiniteScroll
            initialLoad={false}
            pageStart={0}
            loadMore={loadMore}
            hasMore={!loading && total !== logArray.length}
            useWindow={false}
            className={styles.scroll}
          >
            <Timeline
              style={{
                width: '100%',
                paddingLeft: 24,
              }}
            >
              {logArray.map((t: any, i: number) => (
                <Timeline.Item
                  key={t.id}
                  className={`${styles.timeline}  ${i === 0 ? styles.current : ''}`}
                  // color="#ACB1C1"
                >
                  <div className={styles.top_date}>
                    <div className={styles.timeline_left}>
                      {moment(t.date).format('YYYY.MM.DD HH:mm:ss')}
                      <span className={styles.unit}>{`${t.unit} ${
                        t.status == '2' ? '修改' : '新增'
                      }${moment(t.operationYear).format('YYYY')}${
                        !t.isYear ? '月' : '年'
                      }计划`}</span>
                      <span
                        className={[
                          `${styles.normal}`,
                          `${
                            t.status == 1
                              ? styles.complate
                              : t.status == 0
                              ? styles.wait
                              : styles.update
                          }`,
                        ].join(' ')}
                      >
                        {t.planStatus}
                      </span>
                      {t.expand ? (
                        <UpSquareOutlined
                          style={{ color: 'var(--bd-primary)', marginLeft: 12 }}
                          onClick={() => {
                            setLogArray(
                              logArray.map((_t: any, _i: number) => {
                                if (_i === i) {
                                  _t.expand = false;
                                }
                                return _t;
                              }),
                            );
                          }}
                        />
                      ) : (
                        <DownSquareOutlined
                          style={{ color: 'var(--bd-primary)', marginLeft: 12 }}
                          onClick={() => {
                            setLogArray(
                              logArray.map((_t: any, _i: number) => {
                                if (_i === i) {
                                  _t.expand = true;
                                }
                                return _t;
                              }),
                            );
                          }}
                        />
                      )}
                    </div>
                    <div className={styles.timeline_right}>
                      操作人：
                      <div className={styles.name}>{t.operator}</div>
                    </div>
                  </div>
                  {t.expand ? (
                    <>
                      <div className={styles.content}>
                        {!t.isYear ? (
                          <>
                            <div className={styles.title}>
                              {`${moment(t.operationYear).format('YYYY')}年月计划电量`}
                              <span className={styles.after}>单位：MWh</span>
                            </div>
                            <div className={styles.itemBox}>
                              {Object.values(t.data).map((_t: any, _i: number) => {
                                return (
                                  <div className={styles.item} key={_i}>
                                    <div className={styles.top}>{_i + 1}月</div>
                                    <div className={styles.bottom}>
                                      {_i > 8 ? t.data[_i + 1] : t.data['0' + (_i + 1)]}
                                    </div>
                                  </div>
                                );
                              })}
                            </div>
                          </>
                        ) : (
                          <>
                            <div className={styles.yearBox}>
                              <div className={styles.yearTitle}>{`${moment(t.operationYear).format(
                                'YYYY',
                              )}年计划电量`}</div>
                              <div className={styles.power}>{t.yearPlanTotal} MWh</div>
                            </div>
                          </>
                        )}
                      </div>
                    </>
                  ) : (
                    ''
                  )}
                </Timeline.Item>
              ))}
            </Timeline>
          </InfiniteScroll>
        </div>
      )}
    </div>
  );
};
export default HistoryShot;
